package com.xgkj.diyiketang.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.Text;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.data.OrderInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.BuildOrderTask;
import com.xgkj.diyiketang.task.SureOrderStateTask;
import com.xgkj.diyiketang.task.YueZhiFuTask;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.WeiXinPay;
import com.xgkj.diyiketang.yizhibo.Constants;
import com.xgkj.diyiketang.yizhibo.PlayerActivity;
import com.xgkj.diyiketang.yizhibo.PlayerNewActivity;
import com.xgkj.eatshow.wxapi.WXPayEntryActivity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by XCKJ_Paladowow on 2016/9/5.
 */
public class GouMaiKeChengActivity extends BaseActivity implements View.OnClickListener{
    private Context mContext;
    private TextView titleText;
    private TextView topfeeText;
    private TextView teacherText;
    private ImageButton zhifuBtn;
    private RelativeLayout lingqianLayout;
    private ImageView lingqian_check;
    private RelativeLayout weixinLayout;
    private ImageView weixin_check;
    private int mZhifuType = 1;
    private int yuezhifuTaskId = -1;
    private String objectId;
    private TextView feeText;

    private String teacherString;
    private String feeString;
    private String titleString;
    private int type = 1;
    private int orderTaskId = -1;
    private ProgressDialog mProgressDialog;
    private IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    private BroadcastReceiver mWeiXinReceive;
    private String orderNo;
    private String orderBody = "购买课程";
    private int from;
    private TextView biaotiText;
//    private ArrayList<EatShowUserInfo> zhiboList;
//    private int currentPosition ;
    private int confirmOrderTaskId = -1;
    private String buyType;
    private String liveState;
    private String zhibo_play;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goumaikecheng);
        mContext = this;
        msgApi.registerApp(ProtocolConst.APP_ID);
        initView();
    }

    private void initView(){
        Intent intent = getIntent();
        if(intent!=null){
            from = intent.getIntExtra("From",0);
            try {
                if (intent.getStringExtra("TITLE") != null) {
                    titleString = URLDecoder.decode(intent.getStringExtra("TITLE"), "utf-8");

                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            liveState = intent.getStringExtra(Constants.LIVE_STATE);
            zhibo_play = intent.getStringExtra(Constants.ZHIBO_PLAY);
            teacherString = intent.getStringExtra("ZUOZHE");
            feeString = intent.getStringExtra("FEE");
            if (from == 0) {
                buyType = "1";
                orderBody = "购买课程";
                objectId = intent.getStringExtra("videoid");
            }else if (from ==1){
                buyType ="3";
                objectId = intent.getStringExtra(Constants.EXTRA_KEY_VIDEO_ID);
                orderBody = "购买直播课程";
//                zhiboList = (ArrayList<EatShowUserInfo>) getIntent().getSerializableExtra("ZHIBO_LIST");
//                currentPosition = getIntent().getIntExtra("CURRENT_POSITION",0);
            }
        }

        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        biaotiText = (TextView) findViewById(R.id.gameName);
        if (from == 0){
            biaotiText.setText("购买课程");
        }else if (from ==1){
            biaotiText.setText("直播付费");
        }
        titleText = (TextView) findViewById(R.id.kecheng_name);
        titleText.setText(titleString);
        topfeeText = (TextView) findViewById(R.id.topfee);
        topfeeText.setText(feeString);
        teacherText = (TextView) findViewById(R.id.teacher_name);
        try {
            teacherString = URLDecoder.decode(teacherString,"utf-8");
            teacherText.setText("授课教师："+teacherString);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        feeText = (TextView) findViewById(R.id.fee);
        feeText.setText(feeString);

        lingqianLayout = (RelativeLayout) findViewById(R.id.lingqian_layout);
        lingqianLayout.setOnClickListener(this);
        lingqian_check = (ImageView) findViewById(R.id.lingqian_check);
        weixinLayout = (RelativeLayout) findViewById(R.id.weixin_layout);
        weixinLayout.setOnClickListener(this);
        weixin_check = (ImageView) findViewById(R.id.weixin_check);
        zhifuBtn = (ImageButton) findViewById(R.id.baoming_btn);
        zhifuBtn.setOnClickListener(this);
        type = 1;
    }

    private void doYueZhifu() {
        if (yuezhifuTaskId != -1) {
            return;
        }
        YueZhiFuTask task = new YueZhiFuTask(objectId, buyType, feeString,null);
        task.addListener(new ZhiFuTaskEventListener(mContext));
        yuezhifuTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    class ZhiFuTaskEventListener extends ShowToastTaskEventListener {

        public ZhiFuTaskEventListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if(yuezhifuTaskId == taskId) {
                if (data != null) {
//                    odinfo = (OrderInfo) data;
//                    mOrderNo = odinfo.getOrderNo();
//                    Intent intent = new Intent(mContext, BaoMingChengGongActivity.class);
//                    intent.putExtra("ORDERNO", mOrderNo);
//                    intent.putExtra("FEE", mMoney);
//                    startActivity(intent);
                    ToastUtil.showMessage(mContext, "购买成功!");
                    if (from ==1) {
                        Intent intent = new Intent(mContext, PlayerNewActivity.class);
                        intent.putExtra(Constants.EXTRA_KEY_VIDEO_ID, objectId);
                        intent.putExtra(Constants.LIVE_STATE,liveState);
                        intent.putExtra(Constants.ZHIBO_PLAY,zhibo_play);
                        intent.putExtra("type","goumai");
//                        intent.putExtra("ZHIBO_LIST", zhiboList);
//                        intent.putExtra("CURRENT_POSITION", currentPosition);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mContext.startActivity(intent);
                    }
                    finish();
                }
            }else if (orderTaskId == taskId){
                dismissDialog();
                if (data != null) {
                    OrderInfo info = (OrderInfo) data;
                    if (info != null) {
                        orderNo = info.getOrderNo();
                        doWeixinPay();
                    }
                }
            }else if (taskId == confirmOrderTaskId){
                dismissDialog();
                if (data != null) {
                    String status = (String) data;
                    if (status.equals("1")){
                        Intent intent = new Intent(mContext, PlayerNewActivity.class);
                        intent.putExtra(Constants.EXTRA_KEY_VIDEO_ID, objectId);
                        intent.putExtra(Constants.LIVE_STATE,liveState);
                        intent.putExtra(Constants.ZHIBO_PLAY,zhibo_play);
//                        intent.putExtra("ZHIBO_LIST", zhiboList);
//                        intent.putExtra("CURRENT_POSITION", currentPosition);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mContext.startActivity(intent);
                    }else {

                    }
                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            dismissDialog();
            yuezhifuTaskId = -1;
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    }

    private boolean checkInput() {

        if (mZhifuType == -1) {
            Toast.makeText(mContext, R.string.no_check_pay, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lingqian_layout:
                type = 2;
                lingqian_check.setVisibility(View.VISIBLE);
                weixin_check.setVisibility(View.GONE);
                break;
            case R.id.weixin_layout:
                type = 1;
                weixin_check.setVisibility(View.VISIBLE);
                lingqian_check.setVisibility(View.GONE);
                break;

            case R.id.baoming_btn:
                if (type == 2) {
                    doYueZhifu();
                } else if (type == 1) {
                    getOrder();
                }
                break;

        }
    }

    private void getOrder(){
        showProgressDialog();
        BuildOrderTask orderTask = new BuildOrderTask(objectId,buyType,feeString,null,null,null,null,null,null,null,null);
        orderTask.addListener(new ZhiFuTaskEventListener(mContext));
        orderTaskId = getEatShowApp().getTaskManager().addTask(orderTask);
    }

    private void confirmOrderStatus(){
        showProgressDialog();
        SureOrderStateTask confirmOrderTask = new SureOrderStateTask(orderNo);
        confirmOrderTask.addListener(new ZhiFuTaskEventListener(mContext));
        confirmOrderTaskId = getEatShowApp().getTaskManager().addTask(confirmOrderTask);

    }

    private void showProgressDialog(){
        if (mProgressDialog == null){
            mProgressDialog = DialogUtil.showProgressDialog(mContext, getString(R.string.get_ordering), new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    getEatShowApp().getTaskManager().cancelTask(orderTaskId);
                }
            });
        }
    }

    private void dismissDialog(){
        if (mProgressDialog != null && mProgressDialog.isShowing()){
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    private void doWeixinPay(){
        if (!msgApi.isWXAppSupportAPI() || !msgApi.isWXAppInstalled()) {
            ToastUtil.showMessage(mContext, R.string.need_weixin_app);
            return;
        }

        if (mWeiXinReceive == null) {
            mWeiXinReceive = new WeixinReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXPayEntryActivity.WEIXIN_PAY_SUCCESS_ACTION);
            registerReceiver(mWeiXinReceive, filter);
        }
        new WeiXinPay(msgApi, GouMaiKeChengActivity.this, orderNo, orderBody, feeString);
    }

    class WeixinReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isSuccess = intent.getBooleanExtra(ProtocolConst.WEIXINPAY_SUCCESS, false);
            if (isSuccess) {
                if (from == 0) {
                    ToastUtil.showMessage(mContext, "购买成功");
                    finish();
                }else if (from ==1){
                    confirmOrderStatus();
                }
            }
            if (mWeiXinReceive != null) {
                unregisterReceiver(mWeiXinReceive);
                mWeiXinReceive = null;
            }
        }
    }
}
